package com.chenxi.provider;

import com.chenxi.model.SysAuthority;
import com.chenxi.model.SysUser;
import com.chenxi.service.ISysAuthorityService;
import com.chenxi.service.ISysUserService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * Created by BEYOND on 2017/7/13.
 */
@Service(value = "myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysAuthorityService sysAuthorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = Sets.newHashSet();
        SysUser user = sysUserService.loadUserByUsername(username);
        List<SysAuthority> sysAuthorities = sysAuthorityService.loadUserAuthorities(user.getId());
        sysAuthorities.forEach(authority->{
            GrantedAuthority ga = new SimpleGrantedAuthority(authority.getAuthorityCode());
            authorities.add(ga);
        });
        User u = new User(user.getUsername(), user.getPassword(),
                user.isEnabled(),
                user.isAccountNonExpired(),
                user.isCredentialsNonExpired(),
                user.isAccountNonLocked(), authorities);
        return u;
    }
}
